package handle

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"heightFive/Day_exam/day3/userRpc/models"
	user "heightFive/Day_exam/day3/userRpc/proto"

	"net/http"
)

type UserServer struct {
	user.UnimplementedUserServer
}

func (c *UserServer) CreateUser(ctx context.Context, in *user.CreateUserReq) (*user.CreateUserRes, error) {
	users := in.User
	sql, err := UserToSql(users)
	if err != nil {
		fmt.Println("Error creating user", err.Error())
		return nil, err
	}
	err = models.CreateUser(sql)
	if err != nil {
		return nil, err
	}
	return &user.CreateUserRes{Resp: Res(http.StatusOK, "success")}, nil
}

func (c *UserServer) GetInfoByUsername(ctx context.Context, in *user.GetInfoByUsernameReq) (*user.GetInfoByUsernameRes, error) {
	data, err := models.GetInfoByUsername(in.Username)
	if err != nil {
		return nil, err
	}
	return &user.GetInfoByUsernameRes{User: SqlToUser(data)}, nil
}

func Res(code int, msg string) *user.Res {
	return &user.Res{
		Code: int64(code),
		Msg:  msg,
		Data: nil,
	}
}

func SqlToUser(user2 models.User) *user.UserInfo {
	return &user.UserInfo{
		Id:       int64(user2.ID),
		Name:     user2.Name,
		Email:    user2.Email,
		Phone:    user2.Phone,
		Address:  user2.Address,
		Password: user2.Password,
	}
}

func UserToSql(info *user.UserInfo) (models.User, error) {
	return models.User{
		Model:    gorm.Model{},
		Name:     info.Name,
		Email:    info.Email,
		Phone:    info.Phone,
		Address:  info.Address,
		Password: info.Password,
	}, nil
}
